//获取应用实例
const app = getApp();
Page({
    data: {
        carts:[],               // 购物车列表
        hasList:false,          // 列表是否有数据
        totalPrice:0,           // 总价，初始为0
        selectAllStatus:false,    // 全选状态，默认全选
        obj:{
            name:"hello"
        },
        totalNum:0,
        currentIndex:-1,
        choiceStatus:false,
        commonUrl:app.globalData.commonUrl
    },
    onShow() {
        this.getUserSelfCart();
        this.setData({
            totalNum:0,
            currentIndex:-1,
            totalPrice:0,
        });

    },
    goShoppingCart:function(){
        wx.switchTab({
            url:'../BeauSceneryShopCart/BeauSceneryShopCart',
            success:function(){
            },
        })
    },
    getUserSelfCart:function(){
        wx.showLoading({
            title: '加载中',
        });
        app.handlerPost('/api/shopCart/doMyCart.do',{userToken:wx.getStorageSync('sessionid')},"GET").then( (res)=>{
            if(res.data.code=='SUCCESS'){
                let data=res.data.data;
                if(data.length>0){
                    for(var i=0;i<data.length;i++){
                        data[i].selected=false;
                    }
                    this.setData({
                        hasList: true,
                        carts:data
                    });
                }else{
                    this.setData({
                        hasList: false
                    });
                }
            }
            app.fetchAddressList();
        }).catch( (errMsg)=>{
            console.log(errMsg);
        } );
    },
    addNumCart:function(){

    },
    goGoodDetail:function(e){
        let id=e.currentTarget.dataset.id;
        let type=e.currentTarget.dataset.type;
        if(type=='shopcart'){
            wx.navigateTo({
                url: '../goodDetail/goodDetail?id='+id
            })
        }else{
            return;
        }

    },
    removeCart:function(e){
        let id=e.currentTarget.dataset.id;
        let that=this;
        wx.showModal({
            title: '',
            content:'确定删除?',
            success:function(res){
                if(res.confirm){
                    app.handlerPost('/api/shopCart/doRemoveMyCart.do',{userToken:wx.getStorageSync('sessionid'),id:id},"GET").then( (res)=>{
                            wx.showToast({
                                title: '删除成功',
                                icon: 'success',
                                duration: 1000,
                            });
                            that.getUserSelfCart();
                    }).catch( (errMsg)=>{
                        console.log(errMsg);
                    } );
                }else if(res.cancel){
                   console.log('已取消删除');
                }
            },
        });

    },
    updataMyCart:function(amount,id){
        app.handlerPost('/api/shopCart/doUpdateMyCartAmount.do',{userToken:wx.getStorageSync('sessionid'),amount:amount,id:id},"GET").then( (res)=>{
        }).catch( (errMsg)=>{
            console.log(errMsg);
        } );
    },
    onLoad:function(){
        if(wx.getStorageSync('sessionid')==''){
            wx.login({
                success: function (r) {
                    app.login({code:r.code});
                }
            });
        }
        this.getUserSelfCart();
    },
    /**
     * 当前商品选中事件
     */
    selectList(e) {
        const index = e.currentTarget.dataset.index;
        let carts = this.data.carts;
        const selected = carts[index].selected;
        carts[index].selected = !selected;
        if(this.data.currentIndex==index){
            this.setData({
                choiceStatus:!this.data.choiceStatus
            });
            if(this.data.choiceStatus==false){
                this.getUserSelfCart();
                this.getTotalPrice(-1);
            }else{
                this.getUserSelfCart();
                this.getTotalPrice(index);
            }
            return;
        }else{
            this.setData({
                carts: carts,
                currentIndex:index,
                choiceStatus:true
            });
            this.getUserSelfCart();
            this.getTotalPrice(index);
        }
    },
    /**
     * 购物车全选事件
     */
    selectAll(e) {
        let selectAllStatus = this.data.selectAllStatus;
        selectAllStatus = !selectAllStatus;
        let carts = this.data.carts;
        for (let i = 0; i < carts.length; i++) {
            carts[i].selected = selectAllStatus;
        }
        this.setData({
            selectAllStatus: selectAllStatus,
            carts: carts
        });
        this.getUserSelfCart();
        this.getTotalPrice();
    },

    /**
     * 绑定加数量事件
     */
    addCount(e) {
        let id=e.currentTarget.dataset.id;
        const index = e.currentTarget.dataset.index;
        let carts = this.data.carts;
        let amount = carts[index].amount;
        if(amount<100){
            amount = amount + 1;
        }else{
            amount=1;
        }
        carts[index].amount = amount;
        this.setData({
            carts: carts
        });
        this.updataMyCart(amount,id);
        if(this.data.currentIndex==index){
            this.getTotalPrice(index);
        }else{
            return;
        }
    },

    /**
     * 绑定减数量事件
     */
    minusCount(e) {
        let id=e.currentTarget.dataset.id;
        const index = e.currentTarget.dataset.index;
        const obj = e.currentTarget.dataset.obj;
        let carts = this.data.carts;
        let amount = carts[index].amount;
        if(amount <= 1){
            return false;
        }
        amount = amount - 1;
        carts[index].amount = amount;
        this.setData({
            carts: carts
        });
        this.updataMyCart(amount,id);
        if(this.data.currentIndex==index){
            this.getTotalPrice(index);
        }else{
            return;
        }
    },
    bindManual:function(e){
        let id=e.currentTarget.dataset.id;
        const index = e.currentTarget.dataset.index;
        let carts = this.data.carts;
        if(e.detail.value>=1&&e.detail.value<100){
            carts[index].amount = parseInt(e.detail.value);

        }else{
            carts[index].amount=1;
        }
        this.setData({
            carts: carts
        });
        this.updataMyCart( carts[index].amount,id);
        if(this.data.currentIndex==index){
            this.getTotalPrice(index);
        }else{
            return;
        }

    },
    /**
     * 计算总价
     */
    onPullDownRefresh: function () {
        // 小程序提供的api，通知页面停止下拉刷新效果
        let that=this;
        setTimeout(function() {
            that.getUserSelfCart();
            wx.hideNavigationBarLoading();
            wx.stopPullDownRefresh();
        },1000);

    },
    getTotalPrice(index) {
        let totalNum,total;
        let carts = this.data.carts;
        if(index==-1){
            totalNum = 0;
            total=0;
            this.getUserSelfCart();
            this.setData({
                totalNum:totalNum,
                carts: carts,
                totalPrice: 0
            });
        }else{
            totalNum = carts[index].amount;
            total=carts[index].price*totalNum;
            this.getUserSelfCart();
            this.setData({
                totalNum:totalNum,
                carts: carts,
                totalPrice: total.toFixed(2)
            });
        }
        // for(let i = 0; i<carts.length; i++) {
        //     if(carts[i].selected) {
        //         total += carts[i].amount * carts[i].price;
        //         totalNum+=carts[i].amount;
        //     }
        // }
    },
    toBuy() {
        if(this.data.currentIndex==-1){
            wx.showModal({
                title: '提示',
                content:'您还未选择任何商品',
                success:function(res){
                    if(res.confirm){}else if(res.cancel){}
                },
            });
            return;
        }
        let theData=this.data.carts[this.data.currentIndex];
        let makeSureOrder={
            pdtId: theData.goodId,
            stand: theData.name1,
            material: theData.name2,
            colour: theData.name3,
            cartNum: theData.amount,
            price: theData.price,
            name: theData.pdtName,
            imgUrl: theData.pdtImg,
            standCode: theData.code1,
            materialCode: theData.code2,
            colourCode: theData.code3,
        };
        makeSureOrder=JSON.stringify(makeSureOrder);
        wx.navigateTo({
            url: '../makeSureOrder/makeSureOrder?makeSureOrder='+makeSureOrder+'&goodDetailType=1'
        })
    },

});